package com.enterprise.support.utility.generator;

import com.enterprise.support.utility.generator.menu.MenuNode;
import com.enterprise.support.utility.generator.menu.SimpleRootMenuTree;
import com.enterprise.support.utility.generator.pub.MemoryStatus;
import com.enterprise.support.utility.generator.pub.MenuBarView;
import com.enterprise.support.utility.generator.pub.Settings;
import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.PlasticLookAndFeel;
import org.apache.log4j.Logger;

import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
import java.awt.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2011-1-26
 * Time: 10:59:53
 * To change this template use File | Settings | File Templates.
 */
public class CodeGenerator extends JFrame {

    private static final Logger logger = Logger.getLogger(CodeGenerator.class);
    private static CodeGenerator instance;
    private JPanel mainPanel;
    private JPanel bodyPanel, statusPanel;
    private JLabel loginLabel;
    private JMenuBar mainMenuBar;
    private JToolBar mainToolbar;
    private MenuBarView menuBarView;
    private JTree tree;
    protected static final Dimension PREFERRED_SIZE = new Dimension(800, 600);//LookUtils.IS_LOW_RESOLUTION ? new Dimension(1024, 768) : new Dimension(1024, 768);
    /**
     * Describes optional settings of the JGoodies Looks.
     */
    private final Settings settings;

    private void configureUI() {
        // UIManager.put("ToolTip.hideAccelerator", Boolean.FALSE);
        Options.setDefaultIconSize(new Dimension(18, 18));
        Options.setUseNarrowButtons(settings.isUseNarrowButtons());
        // Global options
        Options.setTabIconsEnabled(settings.isTabIconsEnabled());
        UIManager.put(Options.POPUP_DROP_SHADOW_ENABLED_KEY, settings.isPopupDropShadowEnabled());
        UIManager.put("ComboBox.disabledForeground", Color.black);
        UIManager.put("ComboBox.disabledForeground", Color.black);
        UIManager.put("CheckBox.disabledText", Color.black);
        UIManager.put("RadioButton.disabledText", Color.black);
        UIManager.put("Label.disabledForeground", Color.black);
        UIManager.put("Button.disabledText", Color.black);
        UIManager.put("TextField.inactiveForeground", Color.black);
        UIManager.put("FormattedTextField.inactiveForeground", Color.black);
        // Swing Settings
        LookAndFeel selectedLaf = settings.getSelectedLookAndFeel();
        if (selectedLaf instanceof PlasticLookAndFeel) {
            PlasticLookAndFeel.setPlasticTheme(settings.getSelectedTheme());
            PlasticLookAndFeel.setTabStyle(settings.getPlasticTabStyle());
            PlasticLookAndFeel.setHighContrastFocusColorsEnabled(settings.isPlasticHighContrastFocusEnabled());
        } else if (selectedLaf.getClass() == MetalLookAndFeel.class) {
            MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
        }

        // Work around caching in MetalRadioButtonUI
        JRadioButton radio = new JRadioButton();
        radio.getUI().uninstallUI(radio);
        JCheckBox checkBox = new JCheckBox();
        checkBox.getUI().uninstallUI(checkBox);
        try {
            UIManager.setLookAndFeel(selectedLaf);
        } catch (Exception e) {
            System.out.println("Can't change L&F: " + e);
        }
    }

    /**
     * Builds the <code>DemoFrame</code> using Options from the Launcher.
     */
    public void build(String type) {
        setTitle(getWindowTitle());
        menuBarView = createMenuBuilder();
        mainMenuBar = menuBarView.buildMenuBar(settings, null, null);
        setJMenuBar(mainMenuBar);
        setContentPane(buildContentPane(type));
//        setJMenuBar(mainMenuBar);
//        setIconImage(readImageIcon("eye_16x16.gif").getImage());
    }

    protected String getWindowTitle() {
        return " Enterprise 配置";
    }

    protected MenuBarView createMenuBuilder() {
        return new MenuBarView(this);
    }

    /**
     * Builds and answers the content.
     */
    private JComponent buildContentPane(String type) {
        mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(buildToolBar(), BorderLayout.NORTH);
        mainPanel.add(buildMainSplitPanel(type), BorderLayout.CENTER);
        mainPanel.add(buildStatusBar(), BorderLayout.SOUTH);

        return mainPanel;
    }

    private Component buildToolBar() {
        mainToolbar = new JToolBar();
        return mainToolbar;
    }

    private Component buildMainSplitPanel(String type) {

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, buildMenuPanel(), buildBodyPanel(type));
        splitPane.setDividerLocation(180);
        splitPane.setOneTouchExpandable(false);
        splitPane.setContinuousLayout(false);
        splitPane.setDividerSize(0);
        return splitPane;
    }

    private Component buildStatusBar() {
        statusPanel = new JPanel();
        statusPanel.setLayout(new BorderLayout());

        loginLabel = new JLabel();
        updateLoginLabel();
        loginLabel.setAlignmentX(SwingConstants.LEFT);
        loginLabel.setBorder(new CompoundBorder(new CompoundBorder(
                new EmptyBorder(new Insets(1, 1, 1, 1)), new LineBorder(
                Color.GRAY)), new EmptyBorder(new Insets(0, 2, 0, 0))));
        statusPanel.add(loginLabel, BorderLayout.CENTER);

        MemoryStatus memory = new MemoryStatus(statusPanel);
        memory.setAlignmentX(SwingConstants.TRAILING);
        memory.setBorder(new CompoundBorder(new CompoundBorder(new EmptyBorder(
                new Insets(1, 1, 1, 1)), new LineBorder(Color.GRAY)),
                new EmptyBorder(new Insets(1, 1, 1, 1))));
        statusPanel.add(memory, BorderLayout.EAST);

        return statusPanel;
    }

    private Component buildMenuPanel() {

        JPanel menuPanel = new JPanel();
        menuPanel.setLayout(new BorderLayout());
        MenuNode mn = new MenuNode();//LoginHelper.getMenuNode();
        JScrollPane menus = new JScrollPane(new SimpleRootMenuTree(mn).getMenuTree());


        menuPanel.add(menus, BorderLayout.CENTER);
        return menuPanel;
    }

    /**
     * Builds and answers the tabbed pane.
     */
    private Component buildBodyPanel(String type) {
        // JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
        // tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

        // addTabs(tabbedPane);

        // tabbedPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        // return tabbedPane;
        bodyPanel = new JPanel();
        bodyPanel.setLayout(new BorderLayout());
        if ("update".equals(type)) {
            //welcomePanel = new WelcomePanel("update");
            //bodyPanel.add(welcomePanel, BorderLayout.CENTER);
        } else {
            //welcomePanel = new WelcomePanel();
            //bodyPanel.add(welcomePanel, BorderLayout.CENTER);
        }
        return new JScrollPane(bodyPanel);
    }

    public void updateLoginLabel() {
        loginLabel.setText("快速配置,敏捷开发");
    }

    private void showPanel(Class panelClass, Object[] parameters,
                           Class[] paraTypes, boolean changeQueue) {
        bodyPanel.removeAll();
        Constructor<JPanel> constructor = null;
        try {
            constructor = panelClass.getDeclaredConstructor(paraTypes);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        JPanel panel = null;
        try {
            panel = constructor.newInstance(parameters);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        bodyPanel.add(new JScrollPane(panel), BorderLayout.CENTER);
        bodyPanel.revalidate();
        bodyPanel.repaint();

    }

    public void showPanel(JPanel panel) {
        showPanel(panel, true);
    }

    private void showPanel(JPanel panel, boolean changeQueue) {
        bodyPanel.removeAll();
        bodyPanel.add(new JScrollPane(panel), BorderLayout.CENTER);
        bodyPanel.revalidate();
        bodyPanel.repaint();
    }

    /**
     * Constructs a <code>DemoFrame</code>, configures the UI, and builds the
     * content.
     */
    protected CodeGenerator(Settings settings) {
        this.settings = settings;
        configureUI();
        build("create");
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        instance = this;
        logger.debug("System start....");
    }


    public static CodeGenerator getDefault() {
        return instance;
    }


    public static int getBodyWidth() {
        return instance.bodyPanel.getWidth();
    }


    public static int getBodyHeight() {
        return instance.mainPanel.getHeight()
                - instance.mainMenuBar.getHeight()
                - instance.mainToolbar.getHeight()
                - instance.statusPanel.getHeight();

    }

    /**
     * Locates the given component on the screen's center.
     */
    protected void locateOnScreen(Component component) {
        Dimension paneSize = component.getSize();
        Dimension screenSize = component.getToolkit().getScreenSize();
        component.setLocation((screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);
    }

    public static void main(String[] args) {
        Settings settings = Settings.createDefault();
        CodeGenerator instance = new CodeGenerator(settings);
        instance.setSize(PREFERRED_SIZE);
        instance.locateOnScreen(instance);
        instance.setVisible(true);
    }
}
